package util;

import java.util.List;

public class QuerySetPageModel
{
  private List _al = null;
  private int _iCountPerPage = 20;
  private int _iTotalPageCount = 0;
  private long _iTotalRecordCount = 0L;
  private int _iCurPageIdx = 0;

  public QuerySetPageModel(long totalResults, int pageSize, int curPage)
    throws Exception
  {
    this._iTotalRecordCount = totalResults;
    this._iCountPerPage = pageSize;
    this._iCurPageIdx = curPage;

    caculatePageInfo();
  }

  private void caculatePageInfo() throws Exception {
    int tmpPages = 0;

    tmpPages = (int)(this._iTotalRecordCount / this._iCountPerPage);
    if (tmpPages * this._iCountPerPage < this._iTotalRecordCount)
      this._iTotalPageCount = (tmpPages + 1);
    else {
      this._iTotalPageCount = tmpPages;
    }

    if (this._iTotalPageCount == 0) {
      this._iCurPageIdx = 0;

      return;
    }

    if ((this._iCurPageIdx > this._iTotalPageCount) || (this._iCurPageIdx < 1))
      throw new Exception("[QuerySetPageModel] The page index requested(here is " + 
        this._iCurPageIdx + ") is out of range");
  }

  public void setQueryResults(List l)
  {
    this._al = l;
  }

  public List getQueryResults() {
    return this._al;
  }

  public void freePageModel()
  {
    if (this._al != null) {
      this._al.clear();
      this._al = null;
    }
  }

  public int getPageSize()
  {
    return this._iCountPerPage;
  }

  public int getTotalPageCount()
  {
    return this._iTotalPageCount;
  }

  public long getTotalRecordCount()
  {
    return this._iTotalRecordCount;
  }

  public int getCurPageIndex()
  {
    return this._iCurPageIdx;
  }

  public int getPrePageIndex()
  {
    int iRet = this._iCurPageIdx - 1;
    if (iRet >= 1)
      return iRet;

    return -1;
  }

  public int getNextPageIndex()
  {
    if (this._iCurPageIdx >= this._iTotalPageCount)
      return -1;

    return (this._iCurPageIdx + 1);
  }
}